package com.itbooking.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itbooking.core.jwt.JwtOpendIdUtil;
import com.itbooking.mapper.UserMapper;
import com.itbooking.pojo.UserDo;
import com.itbooking.vo.WeixinData;
import com.itbooking.vo.WeixinResultData;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Log4j2
public class WeixinLoginService {

    private static final String WXPATH = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String APPID = "wx2f823cdc8dfba815";
    private static final String APPSCRET = "1aa9b0e277285f9bac0470837e0881e9";

    @Autowired
    private JwtOpendIdUtil jwtOpendIdUtil;
    @Autowired
    private IUserService userService;


    /**
     * wx.login 换取token的信息
     * 注：根据openid来做唯一性判断
     *
     * @return
     */
    public WeixinResultData getWeixinOpendId(String code) {
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String path = WXPATH + "?appid=" + APPID + "&secret=" + APPSCRET + "&js_code=" +code
                + "&grant_type=authorization_code";
        try {
            // 向微信服务器发送get请求获取加密了的内容
            HttpGet httpGet = new HttpGet(path);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse execute = httpclient.execute(httpGet);
            String jsonStr = EntityUtils.toString(execute.getEntity());

            // 解析微信服务器返回给我的数据
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            log.info("2：---->解析微信的信息是 code：{}", code);
            log.info("3：--------->解析微信的信息是：{}", JSON.toJSONString(jsonObject));
            String sessionkey = jsonObject.getString("session_key");//换手机号码的
            String openid = String.valueOf(jsonObject.get("openid"));
            log.info("4：openid:{}，session_key：{}", openid);
            // 把openid作为唯一凭据
            String token = jwtOpendIdUtil.createJWTBySecond(1000 * 60 * 60 * 24 * 365, openid);
            log.info("5：token:{}", token);

            //
            WeixinData weixinData = new WeixinData();
            weixinData.setOpenid(openid);
            weixinData.setSessionKey(sessionkey);
            weixinData.setToken(token);
            //保存微信用户信息注册到数据库中
            UserDo userDo = this.saveUserDo(weixinData);

            // 返回信息
            WeixinResultData weixinResultData = new WeixinResultData();
            weixinResultData.setToken(token);
            weixinResultData.setWeixinData(weixinData);
            weixinResultData.setUserDo(userDo);
            return weixinResultData;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("微信小程序手机号码解密异常，信息如下: {}", e.getMessage());
            return null;
        }
    }


    /**
     * 保存用户
     * @param weixinData
     * @return
     */
    public UserDo saveUserDo(WeixinData weixinData){
        String openid = weixinData.getOpenid();
        // 然后根据openid查询用户是否注册
        UserDo userDo = userService.getUserByOpenid(openid);
        if(userDo==null){
            userDo = new UserDo();
            userDo.setAge(23);
            userDo.setOpenid(openid);
            userDo.setPassword("");
            userDo.setAvatarUrl("a.jpg");
            userDo.setTelephone("15074816437");
            userDo.setNickName(weixinData.getNickname());
            userService.saveUserDo(userDo);
        }else{
            //更新手机和用户信息

        }
        return userDo;
    }

}
